package com.vids.controller;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vids.constant.GlobalConstant;
import com.vids.constant.Urlconstant;
import com.vids.constant.VIIDRespEnum;
import com.vids.model.entity.VIIDServer;
import com.vids.model.param.VIIDServerParam;
import com.vids.model.response.ResponseStatus;
import com.vids.model.vo.VIIDServerVo;
import com.vids.service.IVIIDServer;
import com.github.pagehelper.PageInfo;
import com.vids.utils.BeanUtilss;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Api(value = "联网控制器", tags = "联网控制器")
@RestController
@RequestMapping("/VIID")
public class VIIDController
{
    @Resource
    IVIIDServer iviidServer;

    @ApiOperation(value = "新增联网服务", httpMethod = "POST", notes = "新增联网服务")
    @PostMapping(value = "/VIIDServers", produces = "application/VIID+JSON")
    public Object inset(@RequestBody VIIDServerParam param) throws Exception
    {
        ResponseStatus status = new ResponseStatus(Urlconstant.URL_VIIDSERVERS, VIIDRespEnum.OK.getCode(), new Date());
        if (param == null || param.getVIIDServerObject() == null) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
            return new ResponseEntity<>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
                    HttpStatus.CREATED);
        }
        VIIDServer viidServer = param.getVIIDServerObject();
        validateParams(viidServer, status);
        try {
            VIIDServer vs = iviidServer.findByViidServerId(viidServer.getVIIDServerID());
            if (ObjectUtil.isNotNull(vs)) {
                status.setId(viidServer.getVIIDServerID());
                status.setStatusCode(VIIDRespEnum.INVALID_OPERATION.getCode());
                status.setStatusString("添加联网服务对象已存在！");
                return new ResponseEntity<Map<String, Object>>(
                        BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)), HttpStatus.CREATED);
            }
            if (status.getStatusCode().equals(VIIDRespEnum.OK.getCode())
                    || status.getStatusCode().equals(GlobalConstant.RESPONSE_SUCCESS_CODE)) {
                boolean isInsert = iviidServer.save(viidServer);
                if (isInsert) {
                    status.setStatusString("添加成功！");
                    status.setId(viidServer.getVIIDServerID());
                    return new ResponseEntity<>(
                            BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)), HttpStatus.CREATED);
                }
            }

        } catch (Exception e) {
            status.setStatusCode(VIIDRespEnum.DEVICE_ERROR.getCode());
            status.setStatusString(e.getMessage());
            return status;
        }
        return new ResponseEntity<>(BeanUtilss.objectToMap(BeanUtilss.getResponseModel(status)),
                HttpStatus.CREATED);
    }

    @ApiOperation(value = "修改联网服务", httpMethod = "PUT", notes = "修改联网服务")
    @PutMapping(value = "/VIIDServers", produces = "application/VIID+JSON")
    public Object update(@RequestBody VIIDServerParam param) throws Exception
    {
        ResponseStatus status = new ResponseStatus(Urlconstant.URL_VIIDSERVERS, VIIDRespEnum.OK.getCode(), new Date());
        if (param == null || param.getVIIDServerObject() == null) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "参数为空；");
            return BeanUtilss.getResponseModel(status);
        }
        VIIDServer viidServer = param.getVIIDServerObject();
        validateParams(viidServer, status);
        try {
            QueryWrapper<VIIDServer> ew = new QueryWrapper<>();
            ew.eq("VIIDServerID", viidServer.getVIIDServerID());
            List<VIIDServer> list = iviidServer.list(ew);
            if (list == null || list.size() == 0) {
                status.setStatusString("待修改的数据不存在");
                status.setStatusCode(VIIDRespEnum.INVALID_JSON_CONTENT.getCode());
                return BeanUtilss.getResponseModel(status);
            }
            boolean isInsert = iviidServer.update(viidServer, ew);
            if (isInsert) {
                status.setStatusString("修改成功！");
                status.setId(viidServer.getVIIDServerID());
                return BeanUtilss.getResponseModel(status);
            }
        } catch (Exception e) {
            status.setStatusCode(VIIDRespEnum.DEVICE_ERROR.getCode());
            status.setStatusString(e.getMessage());
            return status;
        }
        return BeanUtilss.getResponseModel(status);
    }

    @ApiOperation(value = "根据id查询联网服务", httpMethod = "GET", notes = "根据id查询联网服务")
    @GetMapping(value = "/VIIDServers/{id}", produces = "application/VIID+JSON;charset=UTF-8")
    public Object get(@PathVariable String id)
    {
        VIIDServer viidServer = null;
        try {
            viidServer = this.iviidServer.findByViidServerId(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (viidServer == null) {
            return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
        }
        VIIDServerParam param = new VIIDServerParam();
        param.setVIIDServerObject(viidServer);
        return param;
    }

    @ApiOperation(value = "根据id删除联网服务", httpMethod = "DELETE", notes = "根据id删除联网服务")
    @DeleteMapping(value = "/VIIDServers/{id}", produces = "application/VIID+JSON")
    public Object del(@PathVariable String id)
    {
        ResponseStatus status = new ResponseStatus(Urlconstant.URL_VIIDSERVERS, VIIDRespEnum.OK.getCode(), new Date());
        try {
            Map<String, Object> map = new HashMap<>(2);
            map.put("VIIDServerID", id);
            boolean idDel = this.iviidServer.removeByMap(map);
            if (idDel) {
                status.setStatusString("删除成功！");
                status.setId(id);
                return BeanUtilss.getResponseModel(status);
            }
        } catch (Exception e) {
            status.setStatusCode(VIIDRespEnum.DEVICE_ERROR.getCode());
            status.setStatusString(e.getMessage());
            return BeanUtilss.getResponseModel(status);
        }
        return BeanUtilss.getResponseModel(status);
    }

    @ApiOperation(value = "获取联网服务集合", httpMethod = "DELETE", notes = "获取联网服务集合")
    @GetMapping(value = "/VIIDServers", produces = "application/VIID+JSON;charset=UTF-8")
    public Object getList(VIIDServerVo viidServer)
    {
        try {
            PageInfo<VIIDServer> pageInfo = this.iviidServer.getList(viidServer);
            List<VIIDServer> list = pageInfo.getList();
            if (list == null || list.size() == 0) {
                return new ResponseEntity<Map<String, Object>>(new HashMap<String, Object>(), HttpStatus.NO_CONTENT);
            }
            return pageInfo.getList();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private boolean checkIp(String ip)
    {
        // ip的正则表达式
        String ipReg = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
        Pattern ipPattern = Pattern.compile(ipReg);
        return ipPattern.matcher(ip).matches();
    }

    private void validateParams(VIIDServer vo, ResponseStatus status)
    {
        if (CharSequenceUtil.isEmpty(vo.getVIIDServerID())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "联网服务编码VIIDServerID必填");
        } else if (CharSequenceUtil.isEmpty(vo.getServerName())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "联网服务Name必填");
        } else if (CharSequenceUtil.isEmpty(vo.getIPAddr())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "IPAddr必填");
        } else if (vo.getIPAddr().length() > 30 || !this.checkIp(vo.getIPAddr())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "IPAddr不合法");
        } else if (CharSequenceUtil.isNotEmpty(vo.getIPV6Addr()) && vo.getIPV6Addr().length() > 64) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "IPAddr长度不能超过64个字符");
        } else if (vo.getPort() == null) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "端口号Port必填");
        } else if (vo.getPort() < 0) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "端口号Port不能小于0");
        } else if (CharSequenceUtil.isEmpty(vo.getUpServerID())) {
            setStatus(status, VIIDRespEnum.INVALID_JSON_CONTENT, "联网服务上级服务器标识符UpServerID必填");
        }
    }


    /**
     * 设置返回值代码和消息 VIID 标准
     *
     * @param res
     * @param e
     * @param field
     */
    protected void setStatus(ResponseStatus res, VIIDRespEnum e, String field) {
        StringBuffer sb = new StringBuffer();
        sb.append(e.getMsg() + "[" + field + "]");
        res.setStatusCode(e.getCode());
        res.setStatusString(sb.toString());
    }

}
